import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'dart:developer'; // for debugger()
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

import 'package:test_flutter/test_http.dart';
import 'package:test_flutter/l10n/localization_intl.dart';
import 'package:test_flutter/test_dialog.dart';
import 'package:test_flutter/test_function_widget.dart';

import 'l10n/localization_original.dart';
import 'ui_login.dart';
import 'test_constrant.dart';
import 'test_buildcontext.dart';
import 'test_container.dart';
import 'test_localization.dart';

void main() {
  // 我们发现onError是FlutterError的一个静态属性，它有一个默认的处理方法 dumpErrorToConsole，
  // 到这里就清晰了，如果我们想自己上报异常，只需要提供一个自定义的错误处理回调即可：
  FlutterError.onError = (FlutterErrorDetails details) {
    // reportError(details); // 自己的处理
  };

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a purple toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        DemoLocalizationsDelegate(),
        DemoLocalizations1Delegate(),
      ],
      supportedLocales: const [
        Locale('en', 'US'),
        Locale('zh', 'CN'),
        Locale('ja', 'JP'),
      ],
      routes: {
        'route_with_param': (context) => const TestParamRoute(),
        'route_login': (context) => const FocusTestRoute(),
        'route_test_constraint': (context) => const ConstraintTestRoute(),
        'route_test_container': (context) => const ContainerTestRoute(),
        'route_test_function_widget': (context) => TestFunctionWidget(),
        'route_test_dialog': (context) => const TestDialogRoute(),
        'route_test_http': (context) => HttpTestRoute(),
        'route_test_localization': (context) => LocalizationRoute(),
      },
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    //从文件读取点击次数
    _readCounter().then((int value) {
      setState(() {
        _counter = value;
      });
    });
  }

  void _incrementCounter() async {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
    // 将点击次数以字符串类型写到文件中
    await (await _getLocalFile()).writeAsString('$_counter');
  }

  Future<String> loadAsset() async {
    return await rootBundle.loadString('assets/config.json');
  }

  void _minusCounter() {
    if (_counter >= 1) {
      setState(() {
        _counter--;
        debugger(when: _counter == 8);
      });
    }
  }

  Future<File> _getLocalFile() async {
    // 获取应用目录
    String dir = (await getApplicationDocumentsDirectory()).path;
    return File('$dir/counter.txt');
  }

  Future<int> _readCounter() async {
    try {
      File file = await _getLocalFile();
      // 读取点击次数（以字符串）
      String contents = await file.readAsString();
      return int.parse(contents);
    } on FileSystemException {
      return 0;
    }
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
            // const Spacer(flex: 1),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text('点击后面的按钮将数字减一：'),
                TextButton(
                  onPressed: _minusCounter,
                  child: const Text('减一'),
                ),
              ],
            ),
            Row(
              children: [
                ElevatedButton(
                  onPressed: () {
                    Navigator.pushNamed(context, 'route_test_constraint');
                  },
                  child: const Text('测试布局约束的例子'),
                ),
                OutlinedButton(
                  onPressed: () {
                    Navigator.pushNamed(context, "route_login");
                  },
                  child: const Text('goto login'),
                ),
              ],
            ),

            Row(
              children: [
                DecoratedBox(
                  decoration: BoxDecoration(
                      gradient: LinearGradient(
                          colors: [Colors.red, Colors.orange.shade700]), //背景渐变
                      borderRadius: BorderRadius.circular(4.0), //3像素圆角
                      boxShadow: const [
                        //阴影
                        BoxShadow(
                            color: Colors.black54,
                            offset: Offset(2.0, 2.0),
                            blurRadius: 4.0)
                      ]),
                  child: TextButton(
                    onPressed: () {
                      Navigator.pushNamed(context, 'route_with_param');
                    },
                    child: const Text(
                      'open route by name',
                      style: TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
                ElevatedButton(
                  onPressed: () {
                    Navigator.pushNamed(context, 'route_test_http');
                  },
                  child: const Text('test http'),
                ),
                ElevatedButton(
                  onPressed: () {
                    Navigator.pushNamed(context, 'route_test_localization');
                  },
                  child: const Text('TestLocale'),
                ),
              ],
            ),

            Row(
              children: [
                TextButton(
                  child: const Text("route with param to appbar"),
                  onPressed: () {
                    //导航到新路由
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (c) {
                        print(c);
                        return const NewRoute(param: 'love');
                      }),
                    );
                  },
                ),
                GestureDetector(
                  child: Image.asset("images/bg_accost_voice.9.png"),
                  onTap: () {
                    Navigator.pushNamed(context, "route_test_container");
                  },
                ),
                IconButton(
                  iconSize: 5,
                  onPressed: () {
                    print('hihihi');
                  },
                  icon: Image.asset('images/ic_clock_notice.png',
                      width: 20, height: 20),
                ),
              ],
            ),
            OutlinedButton(
              onPressed: () =>
                  Navigator.pushNamed(context, 'route_test_function_widget'),
              child: const Text('功能性组件相关的测试~~'),
            ),
            OutlinedButton(
              onPressed: () =>
                  Navigator.pushNamed(context, 'route_test_dialog'),
              child: const Text('对话框组件相关的测试，'),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          debugPrintBeginFrameBanner = true;
          _incrementCounter();
          // debugPrintEndFrameBanner = true;
          debugPrintBeginFrameBanner = false;
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class NewRoute extends StatelessWidget {
  const NewRoute({super.key, this.param});

  final String? param;

  @override
  Widget build(BuildContext context) {
    return SnapAppBar(title: param ?? "");
    // return Scaffold(
    //   appBar: AppBar(
    //     title: Text("New route with $param"),
    //   ),
    //   body: const Center(
    //     child: Text("This is new route"),
    //   ),
    // );
  }
}

class TestParamRoute extends StatelessWidget {
  const TestParamRoute({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("New route"),
      ),
      body: const Center(
        // child: Text("This is new route"),
        child: LayoutBuilderRoute(),
      ),
    );
  }
}

class SnapAppBar extends StatelessWidget {
  SnapAppBar({Key? key, this.title = ""}) : super(key: key);

  final String title;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            // 实现 snap 效果
            SliverAppBar(
              floating: true,
              snap: true,
              expandedHeight: 200,
              forceElevated: innerBoxIsScrolled,
              flexibleSpace: FlexibleSpaceBar(
                background: Image.asset(
                  "images/bg_money_topbar.png",
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ];
        },
        body: Builder(builder: (BuildContext context) {
          return CustomScrollView(
            slivers: <Widget>[buildSliverList(100)],
          );
        }),
      ),
    );
  }
}

// 构建固定高度的SliverList，count为列表项属相
Widget buildSliverList([int count = 5]) {
  return SliverFixedExtentList(
    itemExtent: 50,
    delegate: SliverChildBuilderDelegate(
      (context, index) {
        return ListTile(title: Text('$index'));
      },
      childCount: count,
    ),
  );
}
